/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import httpclient from '@ohos/httpclient';
import router from '@system.router';
import fileIO from '@ohos.fileio';
import Log from '../../log/log';
import featureAbility from '@ohos.ability.featureAbility'


export default {
    data: {
        status: "",
        content: "",
        echoServer: "http://www.yourserverfortest.com",
        fileServer: "http://www.yourserverforfileupload.com",
        fileName: "/test.txt",
        downloadDirectory: "data/misc",
        client: new httpclient.HttpClient.Builder()
            .setConnectTimeout(10000)
            .setReadTimeout(10000)
            .setWriteTimeout(10000)
            .build()
    },
    onInit() {
           },
    showIndexView() {
        router.push({
            uri: 'pages/index/index'
        })
    },
    onComplete: function (result) {
        if (result.response) {
            this.status = result.response.responseCode;
        }
        if (result.response.result)
        this.content = result.response.result;
        else
        this.content = JSON.stringify(result.response);

        Log.showInfo("onComplete -> Status : " + this.status);
        Log.showInfo("onComplete -> Content : " + JSON.stringify(this.content));
    },
    onError: function (error) {
        Log.showInfo("onError -> Error : " + error);
        this.content = JSON.stringify(error);
        Log.showInfo("onError -> Content : " + JSON.stringify(this.content));
    },
    async uploadRequest() {
        let appInternalDir;
        // @ts-ignore
        var fAbility = featureAbility.getContext().getCacheDir();
        await fAbility.then(function (result) {
            appInternalDir = result;
        });
        let fpath = appInternalDir + this.fileName;
        let fd = fileIO.openSync(fpath, 0o102, 0o666);
        // @ts-ignore
        fileIO.writeSync(fd, "text.txt file is uploaded", function (err, bytesWritten) {
        });
        fileIO.closeSync(fd);
        fpath = fpath.replace(appInternalDir, "internal://cache");
        var fileUploadBuilder = new httpclient.FileUpload.Builder()
            .addFile(fpath)
            .addData("name2", "value2")
            .build();
        var fileObject = fileUploadBuilder.getFile();
        var dataObject = fileUploadBuilder.getData();
        let request = new httpclient.Request.Builder()
            .url(this.fileServer)
            .addFileParams(fileObject, dataObject)
            .build();
        this.client.newCall(request)
            .execute()
            .then(this.onComplete)
            .catch(this.onError);
    },
    onDownloadTaskStart: function (downloadTask) {
        downloadTask.on('complete', () => {
            Log.showInfo("download complete");
            this.content = "Download Task Completed";
        })
    },
    onDownloadCustomLocationTask: function (downloadTask) {
        downloadTask.on('complete', () => {
            Log.showInfo("onDownloadTaskStart download complete");
            this.content = "Download Task Completed";
        });
        downloadTask.on("progress", (err, receivedSize, totalSize)=>{
            Log.showInfo("onDownloadTaskStart downloadSize : "+receivedSize+" totalSize : "+totalSize);
            this.content = (receivedSize/totalSize)*100;
        });
    },
    downloadFile() {
        try {
            var request = new httpclient.Request.Builder()
                .download("https://archiveprogram.github.com/assets/img/direction/box2-home.png")
                .build();
            this.client.newCall(request).execute().then(this.onDownloadTaskStart).catch(this.onError);
        } catch (err) {
            Log.showError("downloadFile execution failed - errorMsg : "+err);
        }
    },
    downloadBinaryFile() {
        try {
            var request = new httpclient.Request.Builder()
                .download("https://filesamples.com/samples/font/bin/fontawesome-webfont.bin")
                .build();
            this.client.newCall(request).execute().then(this.onDownloadTaskStart).catch(this.onError);
        } catch (err) {
            Log.showError("downloadBinaryFile execution failed - errorMsg : "+err);
        }
    },
    async downloadCustomLocationExecute() {
        try {
            this.status = "";
            let fPath = this.downloadDirectory + "/sampleExecute.jpg";
            var request = new httpclient.Request.Builder()
                .download("https://imgkub.com/images/2022/03/09/pexels-francesco-ungaro-15250411.jpg", fPath)
                .build();
            this.client.newCall(request).execute().then(this.onDownloadCustomLocationTask).catch(this.onError);
        } catch (err) {
            Log.showError("downloadCustomLocationExecute execution failed - errorMsg : "+err);
        }
    },
    async downloadCustomLocationEnqueue() {
        try {
            this.status = "";
            let fPath = this.downloadDirectory + "/sampleEnqueue.jpg";
            var request = new httpclient.Request.Builder()
                .download("https://imgkub.com/images/2022/03/09/pexels-francesco-ungaro-15250411.jpg", fPath)
                .build();
            this.client.newCall(request).enqueue(this.onDownloadCustomLocationTask, this.onError);
        } catch (err) {
            Log.showError("downloadCustomLocationEnqueue execution failed - errorMsg : "+err);
        }
    }
}